package com.hl.web.fore;

import com.hl.pojo.SystemUser;
import com.hl.service.SystemUserService;
import com.hl.util.MD5Util;
import com.hl.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

@RestController
@RequestMapping("/systemUser")
public class SystemUserController {
    @Autowired
    private SystemUserService service;

    @PostMapping("/add")
    public ResultEntity add(@RequestBody SystemUser systemUser) {
        UUID uuid = UUID.randomUUID();
        String upperCase = uuid.toString().replace("-", "").toUpperCase();
        systemUser.setPassword(MD5Util.encode(systemUser.getPassword()+ upperCase));
        systemUser.setSalt(upperCase);
        if(service.add(systemUser)==1){
            return ResultEntity.ok();
        }else{
            return ResultEntity.noOk();
        }
    }

    @PostMapping("/login")
    public ResultEntity login(@RequestBody SystemUser systemUser) {
        SystemUser user = new SystemUser();
        System.out.println(systemUser.getUsername());
        if(systemUser.getPhoneNumber()!=null){
            user = service.findByPhoneNumber(systemUser.getPhoneNumber());
        }else{
            user = service.findByUsername(systemUser.getUsername());
        }
        if(user!=null && user.getPassword().equals(MD5Util.encode(systemUser.getPassword()+user.getSalt()))){
            return ResultEntity.ok(user);
        }else{
            return ResultEntity.noOk();
        }
    }

    @GetMapping("/findById")
    public ResultEntity findById(Integer id){
        return ResultEntity.ok(service.findById(id));
    }
}
